package com.ds.common.org.expression.personrole;

import com.ds.common.expression.ParseException;
import com.ds.common.expression.function.Function;
import com.ds.common.util.StringUtility;
import com.ds.org.OrgManager;
import com.ds.org.Role;
import com.ds.org.RoleNotFoundException;
import com.ds.server.OrgManagerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * <p>Title: JDSORG组织机构中间件</p>
 * <p>Description: </p>
 * <p>Copyright: jds Copyright (c) 2003-2008</p>
 * <p>Company: www.justdos.net</p>
 *
 * @author wenzhangli
 * @version 2.0
 */
public class GetPersonRoleByNames extends Function {
    public GetPersonRoleByNames() {
        numberOfParameters = 1;
    }

    public void run(Stack stack) throws ParseException {
        checkStack(stack); // check the stack

        Object param2 = stack.pop();

        stack.push(perform(param2));
    }

    protected Role[] perform(Object param1) throws ParseException {
        if (param1 == null) {
            return new Role[0];
        }
        if (param1 instanceof String) {
            OrgManager orgManager = OrgManagerFactory.getOrgManager();

            String names = (String) param1;
            String[] idArr = StringUtility.split(names, ":");
            List result = new ArrayList();
            for (String name : idArr) {
                try {
                    Role role = orgManager.getPersonRoleByName(name);
                    if (role != null) {
                        result.add(role);
                    }
                } catch (RoleNotFoundException e) {
                }

            }
            return (Role[]) result.toArray(new Role[result.size()]);
        }

        throw new ParseException("Invalid parameter type in:" + this.getClass().getName() + ", param1 is " + param1.getClass().getName());
    }
}